import * as OrderApi from "@/api/order/order"
import * as RefundApi from "@/api/order/refund"
import ChannelTypeEnum from "@/common/enum/channelType"
import StoreModel from '@/common/model/Store'
import { cloneObj } from "@/utils/util"

const ACTION_TYPE = {
  // 收货退款
  FINISH_REFUND: 1,
  // 驳回
  FINISH_REJECT: 2
}

export default {
  data() {
    return {
      ACTION_TYPE,
      confirmOrder: {},
      refundCouponList: [],
      tracks: [],
      showPartModal: false,
      partModalText: '',
      hasForce: false
    }
  },
  methods: {
    // 跳转订单详情
    selectOrder(item) {
      const { orderId, refundOrderId, verification, predictPickCompletedTime } = item
      const params = {
        orderId,
        refundOrderId
      }
      if (verification) params.verification = verification
      if (predictPickCompletedTime) params.predictPickCompletedTime = predictPickCompletedTime
      this.$navTo('pages/order/detail', params)
    },
    handleControls(type, item, review) {
      switch (type) {
        case 'scan' : return this.handleScanCode(item)
        case 'receive' : return this.handlePublicFetch(type, item)
        case 'prepare' : return this.handlePublicFetch(type, item)
        case 'start' : return this.handlePublicFetch(type, item)
        case 'finish' : return this.handlePublicFetch(type, item)
        case 'logistics' : return this.logistics(item)
        case 'returnOrder' : return this.returnOrder(item, review)
        case 'refundConfirm' : return this.fetchRefundOrder(item, review)
        case 'way' : return this.setPickUpWay(item)
        case 'cancelOrder' : return this.handleCancelOrder(item)
        case 'partReturn' : return this.handlePartReturn(item)
        case 'returnGoods' : return this.handleReturnGoods(item)
        case 'tracks' : return this.handleTracks(item)
        case 'more' : return this.handleMore(item)
        case 'print' : return this.handlePrint(item)
        case 'select' : return this.selectOrder(item)
      }
    },
    handlePublicFetch(type, item) {
      const { thirdChannelId, channelOrderNo, orderId, shopId, storeId } = item
      OrderApi[type]({
        thirdChannelId,
        channelOrderNo,
        orderId,
        shopId,
        storeId
      }, { load: false, isPrompt: false }).then(() => {
        this.$toast('操作成功')
        this.onRefreshList()
        StoreModel.logs({
          status: 1,
          businessId: channelOrderNo,
          operationType: this.getOperationType(type)
        })
      }).catch(err => {
        this.$toast(`操作失败-${err?.msg}`)
        StoreModel.logs({
          status: 0,
          businessId: channelOrderNo,
          operationType: this.getOperationType(type)
        })
      }).finally(() => {})
    },
    getOperationType(type) {
      switch (type) {
        case 'receive' : return 'order_receive'
        case 'prepare' : return 'order_prepare'
        case 'start' : return 'self_delivery'
        case 'finish' : return 'order_finish'
      }
    },
    // 物流发货
    logistics(item) {
      this.$navTo('orderpages/logistics/index', { orderId: item.orderId })
    },
    // 审核用户退单
    async returnOrder(item, review) {
      const { thirdChannelId, orderId } = item
      // 小程序订单查询消费有礼送券信息
      if (review === 1 && thirdChannelId === ChannelTypeEnum.APPLET.value) {
        this.confirmOrder = { item, review }
        try {
          const consumeCoupon = await OrderApi.getConsumeGiftCoupons(orderId)
          if (consumeCoupon?.data?.length) {
            this.refundCouponList = consumeCoupon.data
            this.$nextTick(() => {
              this.$refs.refundCouponRef.show()
            })
            return
          }
        } catch (e) {}
      }
      this.requestReturnOrder(item, review)
    },
    /**
     * 请求退款接口
     */
    requestReturnOrder(item, review) {
      RefundApi.check({
        thirdChannelId: item.thirdChannelId,
        refundOrderId: item.refundOrderId,
        channelOrderNo: item.channelOrderNo,
        channelRefundOrderNo: item.channelRefundOrderNo,
        refundAmount: item.refundAmount,
        review
      }, { isPrompt: false }).then(res => {
        if (res.data) {
          this.$success('操作成功')
          this.onRefreshList()
          if (review === 2) this.setPickUpWay(item)
          StoreModel.logs({
            status: 1,
            businessId: item.channelOrderNo,
            operationType: 'refund_audit'
          })
        }
      }).catch(err => {
        this.$toast(`操作失败-${err?.msg}`)
        StoreModel.logs({
          status: 0,
          businessId: item.channelOrderNo,
          operationType: 'refund_audit'
        })
      })
    },
    // 消费有礼送券弹窗二次确认
    refundModalConfirm() {
      const { item, review } = this.confirmOrder
      this.requestReturnOrder(item, review)
    },
    handleCancelOrder(item) {
      const { thirdChannelId, orderId, channelOrderNo } = item
      RefundApi.cancelOrder({
        thirdChannelId,
        orderId,
        channelOrderNo,
        force: this.hasForce
      }, { isPrompt: false }).then(() => {
        this.$success('操作成功')
        this.onRefreshList()
        StoreModel.logs({
          status: 1,
          businessId: channelOrderNo,
          operationType: 'order_cancel'
        })
      }).catch(({code, msg}) => {
        if (code === 4000) {
          this.partModalText = msg
          this.showPartModal = true
          this.hasForce = true
        } else {
          this.$toast(msg)
        }
        StoreModel.logs({
          status: 0,
          businessId: channelOrderNo,
          operationType: 'order_cancel'
        })
      })
    },
    fetchRefundOrder(item, review) {
      const { thirdChannelId, channelRefundOrderNo } = item
      const { unConfirm, refundConfirm } = RefundApi
      const fetch = review === ACTION_TYPE.FINISH_REFUND ? refundConfirm : unConfirm
      fetch({
        thirdChannelId,
        channelRefundOrderNo,
      }, { isPrompt: false }).then(({ data }) => {
        if (data) {
          this.$success('操作成功')
          this.onRefreshList()
          StoreModel.logs({
            status: 1,
            businessId: channelRefundOrderNo,
            operationType: 'refund_confirm'
          })
        }
      }).catch(err => {
        this.$toast(`操作失败-${err?.msg}`)
        StoreModel.logs({
          status: 1,
          businessId: channelRefundOrderNo,
          operationType: 'refund_confirm'
        })
      })
    },
    // 扫码核验
    handleScanCode(item) {
      uni.scanCode({
        success: (res) => {
          OrderApi.orderVerify({
            thirdChannelId: item.thirdChannelId,
            orderId: item.orderId,
            channelOrderNo: item.channelOrderNo,
            shopId: item.shopId,
            verification: res.result,
            verifyCheck: true
          }).then(({ data }) => {
            if (data) {
              this.$success('操作成功')
              this.onRefreshList()
              StoreModel.logs({
                context: `自提码：${res.result}`,
                status: 1,
                businessId: item.channelOrderNo,
                operationType: 'self_pick'
              })
            }
          }).catch(err => {
            const { code, msg } = err
            this.$toast(`操作失败-${msg}`)
            if (code === 1001) {
              setTimeout(() => {
                item.verification = res.result
                this.selectOrder(item)
              }, 2000)
            }
            StoreModel.logs({
              status: 0,
              context: `自提码：${res.result}`,
              businessId: item.channelOrderNo,
              operationType: 'self_pick'
            })
          })
        },
      })
    },
    // 设置取货方式
    setPickUpWay(item) {
      const {channelRefundOrderNo, thirdChannelId} = item
      this.$navTo('orderpages/way/index', {
        channelRefundOrderNo,
        thirdChannelId
      })
    },
    // 订单详情展开
    async handleMore(item) {
      item.showMore = !item.showMore
      if (item.details) return
      const fetch = item.refundOrderId ? RefundApi.refundDetail : OrderApi.getOrderDetail
      const id = item.refundOrderId || item.orderId
      const { data } = await fetch(id, { load: false })
      if (data) {
        this.list.forEach(val => {
          if (val.orderId === item.orderId) {
            item.details = data
          }
        })
      }
    },
    // 订单轨迹
    handleTracks(item) {
      const fetch = item.refundOrderId ? RefundApi.getRefundOrderTracks : OrderApi.getOrderTracks
      const id = item.refundOrderId || item.orderId
      fetch(id, { load: false }).then(({ data }) => {
        this.tracks = data.reverse()
        this.$refs.tracksRef.show()
      })
    },
    // 获取部分退的订单详情
    handlePartReturn(item) {
      OrderApi.getOrderDetail(item.orderId, { load: false }).then(({ data }) => {
        if (data) {
          this.confirmOrder = data
          const { thirdChannelId, channelOrderNo, orderGoods } = data
          if (thirdChannelId === ChannelTypeEnum.MT.value) {
            OrderApi.getOrderDetailGoods({ thirdChannelId, channelOrderNo }).then(res => {
              const result = res.data
              if (result) {
                orderGoods.forEach(item => {
                  item.remainingRefundAmount = 0
                  const tmp = result.goodsList.find(val => val.itemId === item.itemId)
                  if (tmp) item.remainingRefundAmount = tmp.remainingRefundAmount
                })
                this.confirmOrder = {
                  ...data,
                  orderGoods
                }
              }
            })
          }
          this.$nextTick(() => {
            this.$refs.partPopupRef.show()
          })
        }
      })
    },
    // 部分退&&整单退
    handlePartConfirm(params) {
      const nParams = cloneObj(params)
      delete nParams.isRefundAll
      nParams.force = this.hasForce
      const { cancelOrder, partReturn } = RefundApi
      const requestFun = params.isRefundAll ? cancelOrder : partReturn
      requestFun(nParams, { isPrompt: false }).then(({ data }) => {
        if (data) {
          this.$success('操作完成')
          this.$refs.partPopupRef.hide()
          this.onRefreshList()
          StoreModel.logs({
            status: 1,
            businessId: nParams.channelOrderNo,
            operationType: params.isRefundAll ? 'order_cancel' : 'part_refund'
          })
        }
      }).catch(({code, msg})=> {
        if (code === 4000) {
          this.partModalText = msg
          this.showPartModal = true
          this.hasForce = true
        } else {
          this.$toast(msg)
        }
        StoreModel.logs({
          status: 0,
          businessId: nParams.channelOrderNo,
          operationType: params.isRefundAll ? 'order_cancel' : 'part_refund'
        })
      })
    },
    // 骑手返货
    handleReturnGoods(item) {
      this.confirmOrder = item
      this.$refs.returnGoodsRef.show()
    },
    // 打印联弹窗
    handlePrint(item) {
      this.confirmOrder = item
      this.$refs.printPopupRef.show()
    },
    // 打印联确认事件
    confirmPrint(ids) {
      uni.showModal({
        content: '是否使用wifi云打印机重打订单？',
        cancelColor: '#999',
        confirmColor: '#2D71FD',
        success: res => {
          if (res.confirm) {
            OrderApi.batchPrint({
              orderIds: [this.confirmOrder.orderId],
              printCopies: ids
            }).then(({ data }) => {
              if (data) this.$success('打印成功')
            }).catch(() => {})
          }
        }
      })
    },
  }
}
